package com.security.intercept;

import com.security.config.JwtConfig;
import com.security.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Nonnull;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 * Created by zn on 2018/4/26.
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtConfig jwtConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    @Nonnull HttpServletResponse response,
                                    @Nonnull FilterChain chain) throws ServletException, IOException {
        log.info("安全请求拦截:{}", request.getRequestURI());
        String token = request.getHeader(jwtConfig.getTokenHeader());
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                Jwt jwt = JwtHelper.decode(token);
                String claims = jwt.getClaims();//{}
                log.info("解析token:{}", claims);
                if (StringUtils.isEmpty(claims)) {
                    setResponse(response, "token解析失败");
                    return;
                }
            } catch (Exception e) {
                log.info("解析token异常:{}", e.getMessage());
                setResponse(response, e.getMessage());
                return;
            }
        }
        chain.doFilter(request, response);
    }

    private void setResponse(HttpServletResponse response, String msg) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setStatus(401);
        response.getWriter().println(msg);
        response.getWriter().flush();
    }

}
